package com.qiaoba.module.file.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.entity.Result;
import com.qiaoba.module.file.entity.SysFile;
import com.qiaoba.module.file.service.SysFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件管理 Web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/19 9:14
 */
@RestController
@RequestMapping("/sys/file")
@RequiredArgsConstructor
@Tag(name = "文件管理")
public class SysFileController {

    /**
     * ${file.uploadPath:} 后面: 代表如果配置文件没有 就设置默认值空串
     * 因为实际项目可能文件存储不是本地模式, 那么就不会有这个配置
     * 如果不设置默认值, 项目就会启动失败
     */
    @Value("${file.uploadPath:}")
    private String uploadPath;

    private final SysFileService sysFileService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public Result upload(MultipartFile file) throws Exception {
        return Result.success(sysFileService.upload("ailanyin-pic", file.getOriginalFilename(), file.getContentType(), file.getSize(), file.getInputStream()));
    }

    @DeleteMapping("/{fileId}")
    @Operation(summary = "删除文件")
    public Result delete(@PathVariable String fileId) {
        sysFileService.delete(fileId);
        return Result.success();
    }

    @GetMapping("/download")
    @Operation(summary = "下载文件-仅【本地模式】需要")
    public void download(HttpServletResponse response, String fileId) throws Exception {
        if (StrUtil.isBlank(uploadPath)) {
            throw new ServletException("download error! uploadPath is null");
        }
        SysFile sysFile = sysFileService.selectById(fileId, false);

        String filename = com.qiaoba.api.file.util.FileUtil.percentEncode(sysFile.getName());
        // 浏览器看到这个标识就会直接下载
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.addHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition,download-filename");
        String contentDispositionValue = "attachment; filename=" + filename + ";" + "filename*=" + "utf-8''" + filename;
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue);
        response.setHeader("download-filename", filename);

        ServletOutputStream outputStream = null;
        try {
            String path = uploadPath + "/" + sysFile.getBucket() + "/" + sysFile.getPath();
            outputStream = response.getOutputStream();
            FileUtil.writeToStream(path, outputStream);
        } finally {
            IoUtil.close(outputStream);
        }
    }

}
